package com.community.backend.controller;
import java.nio.charset.StandardCharsets;
import com.community.backend.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j
@RestController
@RequestMapping("/chat")  // 修改为 /api/chat 与前端的请求一致
@CrossOrigin(origins = "*")
public class ChatController {

    @Autowired
    private ChatService chatService;
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(
            @RequestParam String sessionId,
            @RequestParam String input) {

        SseEmitter emitter = new SseEmitter(300000L);
        AtomicBoolean completed = new AtomicBoolean(false);

        try {
            chatService.streamChat(sessionId, input, chunk -> {
                if (!completed.get()) {
                    try {
                        // 使用 Base64 编码避免中文乱码
                        String encodedChunk = Base64.getEncoder().encodeToString(chunk.getBytes(StandardCharsets.UTF_8));
                        emitter.send(encodedChunk);
                    } catch (IOException e) {
                        completed.set(true);
                        // 发送失败，连接可能已关闭
                    }
                }
            });

        } catch (IOException e) {
            if (!completed.get()) {
                try {
                    String errorEncoded = Base64.getEncoder().encodeToString(("服务错误: " + e.getMessage()).getBytes(StandardCharsets.UTF_8));
                    emitter.send(errorEncoded);
                    emitter.complete();
                } catch (IOException ex) {
                    // 忽略错误
                }
            }
            completed.set(true);
        }

        emitter.onCompletion(() -> {
            completed.set(true);
            log.info("SSE连接完成: {}", sessionId);
        });

        emitter.onTimeout(() -> {
            completed.set(true);
            log.info("SSE连接超时: {}", sessionId);
        });

        emitter.onError((ex) -> {
            completed.set(true);
            log.error("SSE连接错误: {}", sessionId, ex);
        });

        return emitter;
    }
}